package com.momo.consumer;

import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;

import java.util.Arrays;
import java.util.Collections;
import java.util.Properties;

/**
 * @author ：朱博
 * @description：TODO
 * @date ：2021/3/22 21:00
 */
public class MyConsumer {


    public static void main(String[] args) {

            Properties prop = new Properties();

            prop.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG,"192.168.0.105:9092");

            prop.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG,"org.apache.kafka.common.serialization.StringDeserializer");
            prop.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG,"org.apache.kafka.common.serialization.StringDeserializer");

            prop.put(ConsumerConfig.AUTO_COMMIT_INTERVAL_MS_CONFIG,"1000");//自动提交的延迟
            prop.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG,true);//自动提交
            //消费者组
            prop.put(ConsumerConfig.GROUP_ID_CONFIG,"MyGroup2");

            //设置当重有新的消费者组的时候 重新消费消费之前的所有数据(注意 这里有可能会有雨 数据超过了7天就会被Kafka删除这时候无法消费)
            prop.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG,"earliest");

            KafkaConsumer<String,String> consumer = new KafkaConsumer<String, String>(prop);
            //订阅主题
            consumer.subscribe(Collections.singletonList("mycallback"));
        //循环拉去消息
        for(;;){
            //获取数据(添加延迟,防止空转多久拉去一次数据)
            ConsumerRecords<String, String> poll = consumer.poll(100);
            poll.forEach(x -> {
                System.out.println("*****************************************************");
                System.out.println("key-->"+x.key());
                System.out.println("value-->"+x.value());
                System.out.println(x.partition()+"分区"+"offset-->"+x.offset());
                System.out.println("*****************************************************");
            });
        }

    }
}
